package com.tegistuff.webos.run;

import com.intellij.execution.ExecutionException;
import com.intellij.execution.ExecutionManager;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.CommandLineState;
import com.intellij.execution.filters.TextConsoleBuilder;
import com.intellij.execution.filters.TextConsoleBuilderFactory;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManager;

/**
 * WebOSRunningState.java
 *
 * Copyright (C) 2012 Timo Tegtmeier.
 * Copyright (C) 2011 Janni Kovacs.
 * All rights reserved.
 */
public class WebOSRunningState extends CommandLineState {

	private ExecutionEnvironment executionEnvironment;
	private Executor executor;

	public WebOSRunningState(Executor executor, ExecutionEnvironment executionEnvironment) {
		super(executionEnvironment);
		this.executor = executor;
		this.executionEnvironment = executionEnvironment;
		Project project = executionEnvironment.getProject();
		TextConsoleBuilder builder = TextConsoleBuilderFactory.getInstance().createBuilder(project);
		builder.setViewer(false);
		this.setConsoleBuilder(builder);
	}

	@Override
	protected OSProcessHandler startProcess() throws ExecutionException {
        WebOSRunConfiguration configuration = (WebOSRunConfiguration)getRunnerSettings().getRunProfile();
        WebOSRunner.BuildMode buildMode = configuration.FollowLogs
                ? WebOSRunner.BuildMode.BUILD_RUN_LOG
                : WebOSRunner.BuildMode.BUILD_AND_RUN;
        WebOSRunner runner = new WebOSRunner(executionEnvironment.getProject(),
                configuration, buildMode);

        OSProcessHandler processHandler = runner.getProcessHandler();
        final boolean finalAppAlreadyRunning = runner.getIsAppAlreadyRunning();

        processHandler.addProcessListener(new ProcessAdapter() {

            @Override
            public void processTerminated(ProcessEvent event) {
                if (finalAppAlreadyRunning) {
                    RunContentDescriptor contentDescriptor = ExecutionManager.getInstance(executionEnvironment.getProject()).
                            getContentManager().findContentDescriptor(executor, event.getProcessHandler());
                    if (contentDescriptor != null) {
                        final Content content = contentDescriptor.getAttachedContent();
                        ApplicationManager.getApplication().invokeLater(new Runnable() {
                            public void run() {
                                String oldName = content.getDisplayName();
                                ContentManager manager = content.getManager();

                                manager.removeContent(content, true);
                                Content oldContent = manager.findContent(oldName);
                                if (oldContent != null)
                                    manager.setSelectedContent(oldContent);
                            }
                        });
                    }
                }
            }
        });
        return processHandler;
	}

    public OSProcessHandler createProcessWithoutLogging() throws ExecutionException {
        WebOSRunner runner = new WebOSRunner(executionEnvironment.getProject(),
                (WebOSRunConfiguration) getRunnerSettings().getRunProfile(),
                WebOSRunner.BuildMode.BUILD_AND_RUN);

        return runner.getProcessHandler();
    }

    public OSProcessHandler createLogOnlyProcess() throws  ExecutionException {
        WebOSRunner runner = new WebOSRunner(executionEnvironment.getProject(),
                (WebOSRunConfiguration) getRunnerSettings().getRunProfile(),
                WebOSRunner.BuildMode.LOG_ONLY);

        return runner.getProcessHandler();
    }
}
